package com.gogowan.agroenterprise.contorl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import android.util.Log;

import com.gogowan.agroenterprise.MyApplication;

/**
 * http通讯处理
 * 
 * @author zk
 * 
 */
public class HTTPCommit{

	private HttpURLConnection httpURLConnection;

	/**
	 * 超时时间
	 */
	private final static int timeOut = 180000;

	/**
	 * 通讯地址
	 */
	private String url;

	protected void finalize() {
		// TODO: implement
	}

	/**
	 * 得到地址
	 * 
	 * @return 地址
	 */
	public String getUrl() {
		return url;
	}

	/**
	 * 设置地址
	 * 
	 * @param
	 */
	public void setUrl(String newUrl) {
		url = newUrl;
	}

	/**
	 * 构�?通讯处理�?
	 * 
	 * @param
	 */
	public HTTPCommit(String connectionURL) {
		this.url = connectionURL;
	}

	/**
	 * get提交
	 * 
	 * @param timeout
	 *            超时时间
	 * @return 字符�?
	 */
	public String GetCommit(int timeout) {
		int HTTPCode = 0;
		URL urls = null;
		InputStream stream = null;
		InputStreamReader streamReader = null;
		BufferedReader bufferedReader = null;

//		try {
//			urls = new URL(url);
//			HttpURLConnection connection = null;
//			connection = (HttpURLConnection) urls.openConnection();
//			connection.setConnectTimeout(timeout);
//			connection.setReadTimeout(timeout);
//			connection.setRequestProperty("X-Access-Token",
//					MyApplication.mSettings.getString("token",""));
//			connection.setRequestMethod("GET");
//			connection.setDoInput(true);
//			connection.setDoOutput(true);
//
//			if ((HTTPCode = connection.getResponseCode()) == HttpURLConnection.HTTP_OK) {
//				stream = connection.getInputStream();
//				streamReader = new InputStreamReader(stream, "UTF-8");
//				bufferedReader = new BufferedReader(streamReader);
//				String str = bufferedReader.readLine();
//				stream.close();
//				streamReader.close();
//				bufferedReader.close();
//				return str;
//			}
//		} catch (SocketTimeoutException ste) {
//			// ste.printStackTrace();
//			// Log.e("异常信息", ste.getMessage());
//		} catch (SocketException ssocketex) {
//			// Object xx=null;
//			// if(ssocketex != null)
//			// {
//			// Log.e("异常信息", ssocketex.getMessage());
//			// }
//		} catch (MalformedURLException e) {
//			// TODO Auto-generated catch block
//			if (e != null) {
//				e.printStackTrace();
//				Log.e("异常信息", e.getMessage());
//			}
//		} catch (ProtocolException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//			Log.e("异常信息", e1.getMessage());
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			Log.e("异常信息", e.getMessage());
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			Log.e("异常信息", e.getMessage());
//		} catch (Throwable ex) {
//			Log.e("异常信息", ex.getMessage());
//		} finally {
//			try {
//				if (stream != null)
//					stream.close();
//				if (streamReader != null)
//					streamReader.close();
//				if (bufferedReader != null)
//					bufferedReader.close();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
		BufferedReader reader=null;
		HttpURLConnection connection=null;
		try {
			// 构建URL对象

			URL url1 = new URL(url);

			// 打开HttpURLConnection连接
			connection = (HttpURLConnection) url1.openConnection();

			// 设置请求方法
			connection.setRequestMethod("GET");

			// 设置请求头
			connection.setRequestProperty("X-Access-Token",
					MyApplication.mSettings.getString("token",""));

			// 发送请求并获取响应
			int responseCode = connection.getResponseCode();

			// 读取服务器响应的数据
			reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			StringBuilder response = new StringBuilder();
			while ((line = reader.readLine()) != null) {
				response.append(line);
			}
			reader.close();

			// 关闭连接
			connection.disconnect();

			// 处理响应数据

			return response.toString();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 关闭连接
			connection.disconnect();
		}
		return null;
	}

	/**
	 * post提交
	 * 
	 * @param commitData
	 *            提交数据
	 * @param timeout
	 *            超时时间
	 * @return 字节数组
	 */
	public byte[] PostCommit(String commitData, int timeout) {
		int HTTPCode = 0;
		URL urls = null;
		InputStream stream = null;
		InputStreamReader streamReader = null;
		BufferedReader bufferedReader = null;
		BufferedWriter inputstream = null;

		try {
			urls = new URL(url);
			HttpURLConnection connection = null;
			connection = (HttpURLConnection) urls.openConnection();
			connection.setConnectTimeout(timeout);
			connection.setReadTimeout(timeout);
			connection.setRequestProperty("Content-Type",
					"application/json;charset=utf-8");
			connection.setRequestMethod("POST");
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setRequestProperty("X-Access-Token", MyApplication.mSettings.getString("token",""));
//			inputstream = connection.getOutputStream();
			// inputstream.write(json.getBytes());
			// 加密
			// String st=StringUtil.Encrypt(json);
			// inputstream.write(Encrypt(commitData).getBytes("utf-8"));
//			inputstream.write(commitData.getBytes("utf-8"));
			inputstream = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
			inputstream.write(commitData);
			inputstream.close();
			// connection.connect();
			if ((HTTPCode = connection.getResponseCode()) == HttpURLConnection.HTTP_OK) {
				stream = connection.getInputStream();
				streamReader = new InputStreamReader(stream, "UTF-8");
				bufferedReader = new BufferedReader(streamReader);
				// String str = bufferedReader.readLine();
				// 解密
				String str;
				// if(isEncrypt)
				// {
				// str=bufferedReader.readLine();
				// //Log.d("contentlength", ""+str.length());
				// str=StringUtil.Decrypt(str);
				// }
				// else
				// {
				str = bufferedReader.readLine();
				// }
				return str.getBytes("UTF-8");
			}

		} catch (SocketTimeoutException ste) {
			// ste.printStackTrace();
			try {
				return "请求超时".getBytes("utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} catch (SocketException se) {
			// if(se!=null)
			// se.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Throwable ex) {
			// Log.d("no", ex.getMessage());
		} finally {
			try {
				if (stream != null)
					stream.close();
				if (streamReader != null)
					streamReader.close();
				if (bufferedReader != null)
					bufferedReader.close();
				if (inputstream != null)
					inputstream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * get提交
	 * 
	 * @return 字符�?
	 */
	public String GetCommit() {
		String str = GetCommit(timeOut);
		return null;
	}

	/**
	 * post提交
	 * 
	 * @param commitData
	 *            提交数据
	 * @return 字节数组
	 */
	public byte[] PostCommit(String commitData) {
		byte[] b = PostCommit(commitData, timeOut);
		return b;
	}
}